package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    //用于存储全局变量:
    private Long orderId_;
    private String number_;


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional//多表操作
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        log.info("服务层提交订单:{}", ordersSubmitDTO);
        //处理业务异常
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);//这时用户刚下单,还没有支付,暂时设定未支付
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//利用系统时间戳进行订单号的生成,uuid也可以,或者雪花算法
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setUserName(userMapper.getById(userId).getName());
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        orders.setAddress(address.getProvinceName()+address.getCityName()+address.getDistrictName());

        orderMapper.insert(orders);
        //向订单明细表插入n条数据
        //使用集合批量插入效率更高
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for(ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//设置当前订单明细关联的订单id,这里需要在xml文件中设置返回id数据
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //清空当前用户的购物车数据
        shoppingCartMapper.clean(userId);
        //封装VO返回结果

        orderId_=orders.getId();
        number_= orders.getNumber();
        log.info("获取到订单号,{}",number_);
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        WeChatPayUtil weChatPayUtil = new WeChatPayUtil();
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
//    }


    /**

     * 订单支付

     *

     * @param ordersPaymentDTO

     * @return

     */

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {

        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//        ordersPaymentDTO.getOrderNumber(), //商户订单号
//        new BigDecimal(0.01), //支付金额，单位 元
//        "苍穹外卖订单", //商品描述
//        user.getOpenid() //微信用户的openid);
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderId_);

        //跳过了微信支付接口,无法判定是否支付成功,这里直接调用支付成功的方法,创建全局变量,在创建订单的时候就保存订单信息
        log.info("跳过判定，直接成功。订单号为,{}",number_);
        paySuccess(number_);

        return vo;

    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过WebSocket想客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type", 1);//1来单提醒   2客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content", "订单号："+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        log.info("向管理端广播接单提醒：,{}",jsonString);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    @Transactional
    public PageResult pageQuery(Integer page,Integer pageSize,Integer status) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setPhone(null);//todo手机号等参数

        Page<Orders> ordersList = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        if(ordersList != null && !ordersList.isEmpty()) {
            for(Orders orders : ordersList) {
                Long OrderId = orders.getId();
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(OrderId);

                OrderVO vo = new OrderVO();
                BeanUtils.copyProperties(orders, vo);
                vo.setOrderDetailList(orderDetailList);
                orderVOList.add(vo);
            }
        }
        return new PageResult(ordersList.getTotal(),orderVOList);
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        //依据订单id查询信息
        Orders orders = orderMapper.getById(id);
        //查询detail
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    @Override
    @Transactional
    public void cancel(Long OrderId) throws Exception {
//        待支付和待接单状态下，用户可直接取消订单
//        商家已接单状态下，用户取消订单需电话沟通商家
//        派送中状态下，用户取消订单需电话沟通商家
//        如果在待接单状态下取消订单，需要给用户退款
//        取消订单后需要将订单状态修改为“已取消”
        Orders orderDB = orderMapper.getById(OrderId);
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已结单 4派送中 5已完成 6已取消
        if(orderDB.getStatus()>2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(orderDB.getId());

        //判断是否处于待接单状态
        if (orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信退款接口
//            WeChatPayUtil.refund(
//                    orderDB.getNumber(),//获取商户订单号
//                    orderDB.getNumber(),//商户退款单号
//                    new BigDecimal("0.01"),//退款金额
//                    new BigDecimal("0.01")//原订单金额
//            );
            //将订单状态更改退款
            //其他退款情况另外添加
            orders.setPayStatus(Orders.REFUND);

        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);
    }

    @Override
    public void reprtiton(Long id) {
        //再来一单就是将原订单中的商品重新添加到购物车中
        Orders orders = orderMapper.getById(id);
        Long OrderId = orders.getId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(OrderId);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersList = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        if(ordersList != null && !ordersList.isEmpty()) {
            for(Orders orders : ordersList) {
                Long OrderId = orders.getId();
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(OrderId);

                OrderVO vo = new OrderVO();
                BeanUtils.copyProperties(orders, vo);
                vo.setOrderDetailList(orderDetailList);
                orderVOList.add(vo);
            }
        }
        return new PageResult(ordersList.getTotal(),orderVOList);
    }

    @Override
    public OrderStatisticsVO getStatics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待派送数量
        orderStatisticsVO.setConfirmed(orderMapper.getNumOfConfirmed());
        //派送中数量
        orderStatisticsVO.setToBeConfirmed(orderMapper.getNumOfToBeConfirmed());
        //待接单数量
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getNumOfDeliveryInProgress());
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //实现接单方法,首先按照id取出对象,判断非空,然后更改接单状态
        Orders orders = orderMapper.getById(ordersConfirmDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus()>2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus()>2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(orders);
    }

    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus()!=3) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus()!=3) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus()!=4) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Map map = new HashMap();
        map.put("type", 2);//1来单提醒   2客户催单
        map.put("orderId",id);
        //获取订单号
        Orders orders =orderMapper.getById(id);
        map.put("content", "订单号："+orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        log.info("向管理端广播接单提醒：,{}",jsonString);
        webSocketServer.sendToAllClient(jsonString);
    }


}

